package jvlite.filter;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import myJlite.entity.StaffVO;
import jvlite.core.JLiteContext;
import jvlite.util.StrUtil;

public class FilterRequestContext {

	private ServletContext context;
	private HttpSession session;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map<String, Cookie> cookies;

	private final static ThreadLocal<FilterRequestContext> contexts = new ThreadLocal<FilterRequestContext>();

	/**
	 * @param ctx
	 * @param req
	 * @param res
	 */
	public static FilterRequestContext begin(ServletContext ctx,
			HttpServletRequest req, HttpServletResponse res) {
		FilterRequestContext rc = new FilterRequestContext();
		rc.context = ctx;
		rc.request = req;
		rc.response = res;
		rc.session = req.getSession(false);
		rc.cookies = new HashMap<String, Cookie>();
		Cookie[] cookies = req.getCookies();
		if (StrUtil.objNotEmpty(cookies)){
			for (Cookie ck : cookies) {
				rc.cookies.put(ck.getName(), ck);
			}
		}
		contexts.set(rc);
		return rc;
	}

	// get the ThreadLocal
	public static FilterRequestContext get() {
		return contexts.get();
	}

	public void end() {
		this.context = null;
		this.request = null;
		this.response = null;
		this.session = null;
		this.cookies = null;
		contexts.remove();
	}

	public ServletContext getContext() {
		return context;
	}

	public void setContext(ServletContext context) {
		this.context = context;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public Map<String, Cookie> getCookies() {
		return cookies;
	}

	public void setCookies(Map<String, Cookie> cookies) {
		this.cookies = cookies;
	}

}